<?php

/**
 * 菜单模型
 * @author renpper
 * @date 2014-12-30
 * @modify 2015-1-4
 */

namespace Admin\Model;
use Lib\Model;

class MenuModel extends Model {

	public function _initialize() {
		$this->table = 'menu';
	}

	/**
	 * 获得菜单列表
     */
	public function getList(){
		return $this->field('id,name,url,parent,level,target,width,height')->order('id ASC')->select();
	}
   
	/**
     * 获得系统菜单
     */
	public function getMenu(){
   		$menus = $this->getList();
 		return $this->buildTree($menus);
	}
   
   
	/**
     * 获得菜单子节点
     * @param Array $datas 菜单数组
     * @param Int $id 模块ID
     * @param Int 树节点类型
     * @return Array $childs 子节点
     */
	private function getChilds($datas, $id, $type){
		if(is_array($datas)){
   			foreach($datas as $d){
   				if($d['parent'] == $id){
					if($type==1 && $d['level']==1){
						continue;
					}else{
						$childs[] = $d;
					}	
				}		
   			}
   		}
		return isset($childs)?$childs:'';
	}
   
   
    /**
	 * 创建树节点
	 * @param Array $datas 菜单数组
	 * @param Int $id 模块ID
     * @param Int 树节点类型
     * @return Array $childs 子节点
     */
	public function buildTree($datas, $id=0, $type=0){
		$childs = $this->getChilds($datas, $id, $type);
   		if($childs == null){
   			return false;
   		}
   		
   		foreach($childs as $k=>$child){
  			if($recur_array = $this->buildTree($datas, $child['id'], $type)){
   				$childs[$k]['childs'] = $recur_array;
   			}
   		}
   		return $childs;
	}
   
   
	/**
     * 根据角色找到相应的模块
     */
	 public function findModuleByRoleID($role_id){
   		if($modules = M('role')->field('module_ids')->where("roleid=$role_id")->select()){
   			foreach($modules as $module){
   				$data[$module['moduleid']] = '';
   			}
   		}
   		return $data;
	}
   
	/**
	 * 取得父菜单id
	 */
	public function getParentMenu($data){
		if(empty($data)){
			return false;
		}
		
		$menus = $this->getList();
		function getParentId($menus, $parent_id, &$parents){
			if(is_array($menus))
			foreach($menus as $k=>$m){
				$id = $m['id'];
				if($id == $parent_id){
					$parent_id = $m['parent'];
					if(!array_key_exists($id, $parents)){
						$parents[$id] = $m;
						if($parent_id != 0){
							getParentId($menus, $parent_id, $parents);
						}
					}
					break;
				}
			}
		}
		
		$all_menus = array();
		foreach($data as $d){
			getParentId($menus, $d, $all_menus);
		}
		return $all_menus;
	}
}
?>